document.write('<script type="text/javascript" src="../common/js/crypto-js/crypto-js.js"></script>');
document.write('<script type="text/javascript" src="../common/js/miniprogram-sm-crypto/sm3.js"></script>');
document.write('<script type="text/javascript" src="../common/js/miniprogram-sm-crypto/sm4.js"></script>');
document.write('<script type="text/javascript" src="../common/js/crypto.js"></script>');
document.write('<script type="text/javascript" src="../common/js/base64.js"></script>');

document.write('<script type="text/javascript" src="../../common/js/crypto-js/crypto-js.js"></script>');
document.write('<script type="text/javascript" src="../../common/js/miniprogram-sm-crypto/sm3.js"></script>');
document.write('<script type="text/javascript" src="../../common/js/miniprogram-sm-crypto/sm4.js"></script>');
document.write('<script type="text/javascript" src="../../common/js/crypto.js"></script>');
document.write('<script type="text/javascript" src="../../common/js/base64.js"></script>');

(function($) {
	var timeoutInt = 15000 //超时时间15秒
	var token = '', overTime = '';
	var method = 'nurmgapp.appinterface.requestdata'
	$.DHCWebService = function(paramDict, successBlock, failureBlock) {
		//console.log(paramDict.params,paramDict.method);
		DHCGetToken(function(){
			var xhr = new XMLHttpRequest();
			console.log(JSON.stringify(xhr))
			console.log("11111")
			xhr.responseType = 'json';
			xhr.timeout = timeoutInt;
			xhr.onload = function(e) {
				var result = e.target.response;
				var resultDic = eval(result);
				if (result['code'] == '10000') {
					var data = result['data']||'';
					if(data == ''){
						failureBlock('data is null');
						return;
					}
					var dataStr = decryptSM(data);
					var dataDict = JSON.parse(dataStr)
					dataDict = dataDict['RequestDataResult']
					//dataStr = dealDecryptStr(dataStr);//\n和&
					dataDict = eval('(' + dataDict + ')');
					successBlock(dataDict); //返回原始数据，根据情况解析
				}else{
					if (result['code'] == '5001') {
						localStorage.removeItem('token');
						localStorage.removeItem('overdue');
						DHCGetToken(function(){},function(){})
					}
					failureBlock(result['msg']||'');
				}
			} 
			xhr.onerror = function(e) {
				failureBlock('服务器请求错误');
			}
			xhr.onabort = function(e) {
				failureBlock('服务器请求中断');
			}
			xhr.ontimeout = function(e) {
				failureBlock('服务器请求超时');
			}
			var nonceStr = new Date().getTime()+''; //随机数 可为当前时间戳
			var biz_contentStr = JSON.stringify(paramDict);
			var biz_contentSM4 = encryptSM(biz_contentStr);
			//console.log(biz_contentSM4)
			// 发送HTTP请求
			var jsonDict = {
				"app_id": APPID,
				"biz_content":paramDict,
				"method": method,
				"token": token,
				"token_type": "api_credentials",
				"version": "v1.0",
				"nonce_str":nonceStr
			};
			jsonDict['sign'] = encryptSMSign(jsonDict)
			jsonDict['biz_content'] = biz_contentSM4
			var jsonStr = JSON.stringify(jsonDict);
			console.log(JSON.stringify(xhr))
			xhr.open("POST", APIURL);
			xhr.setRequestHeader('Content-Type', 'Application/json');
			//console.log(jsonStr)
			xhr.send(jsonStr);
		},function(err){
			failureBlock(err);
			console.error(JSON.stringify(xhr))
		})
	}
	
	function DHCGetToken(successBlock, failureBlock) {
		if (APPID == "") {
			setAppKeys();
		}
		if (!IsTokenExpires()) { //没有过期
			successBlock();
			return
		}
		var xhr= new XMLHttpRequest();
		console.log("1111")
		xhr.timeout = timeoutInt;
		xhr.withCredentials = false;
		
		var header = APPID + ':' + APPKEY;
		var headerStr = base64.encode(header);
		xhr.responseType = 'json';
		xhr.onload = function(e) {
			if(e.target.response == null) {
				failureBlock('token response is null');
				return;
			}
			//console.log(JSON.stringify(e.target.response))
			var tokenStr = e.target.response['access_token'];
			var remain_time = e.target.response['remain_time']+'';
			if(tokenStr) {
				token = tokenStr
				localStorage.setItem('token', tokenStr);
				if (remain_time == '0') {
					overTime = '0'
					localStorage.setItem('overdue', '0');//长期token
					successBlock();
					return;
				}
				var overInt = parseInt(remain_time)*1000;
					overTime = (new Date().getTime() + (overInt - 60000))+'' //提前一分钟开始获取新的token
				localStorage.setItem('overdue', overTime);
				successBlock();
			} else {
				failureBlock("未获取到token");
			}
		}
		xhr.onerror = function(e) {
			failureBlock('token server is error'+JSON.stringify(e));
			console.log(JSON.stringify(e))
		}
		xhr.onabort = function(e) {
			failureBlock('token is abort');
		}
		xhr.ontimeout = function(e) {
			failureBlock('token is timeout');
		}
		console.log(xhr)
		console.log("2222")
		xhr.open("GET", TokenUrl);
		xhr.setRequestHeader('Content-Type', 'application/json');
		xhr.setRequestHeader('Authorization', headerStr);
		// 设置请求头以允许跨域
		//xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
		console.log(headerStr)
		//"NTdhYTU3MjUtMWRhZS1mZDdjLTA0MDEtYzJhYmJjNDZjN2ZiOjA1MmZjNDYzNmNkZmNiZDhiYzc4OGUwZjdmZTc3ZTQ2"
		console.log("333")
		xhr.send();
		console.log(xhr)
		console.log("1111")
	}
	$.checkUrlReal = function (url,successBlock,failureBlock){
		var xhr
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					successBlock()
					xhr = null;
				}else{
					xhr = null;
					failureBlock()
				}
			}
		}

		xhr.open("GET", url);
		// 发送HTTP请求
		xhr.send();
	}
	//是否过期 true 过期 false 未过期
	function IsTokenExpires(){
		if (overTime == '') {
			overTime = localStorage.getItem('overdue')||'';
			token = localStorage.getItem('token')||'';
		}
		if (overTime == '') {
			return true
		}
		if (overTime == '0') { //长期
			return false
		}
		var curr = new Date().getTime()+''
		if (overTime <= curr) { //过期了 提前一分钟
			return true
		}
		return false
	}
	function xmlDealSpecial(str){
		var destStr = str;
		if (str.indexOf('&') != -1) {
			var arr = str.split('&')
			destStr = arr.join('&amp;')
		}
		if (destStr.indexOf('<') != -1) {
			var arr = destStr.split('<')
			destStr = arr.join('&lt;')
		}
		if (destStr.indexOf('>') != -1) {
			var arr = destStr.split('>')
			destStr = arr.join('&gt;')
		}
		return destStr
	}
	function setAppKeys(){
		// if ((plus.os || {name: /iPhone|iPad|iPod/i.test(navigator.userAgent) ? 'iOS' : 'Android'}).name == 'iOS') {
		// 	APPID = "d0cc070e-0502-c105-0b48-5e4f1c823457"
		// 	APPKEY = "fb6249a7cd59403992dbb06979898ed8";
		// 	CRYPTO_SM3_KEY = 'XOQI0ELztQs4ZkgB'
		// 	CRYPTO_SM4_KEY = 'CftOfGfnNnnaTpxk'
		// }else{
			APPID = "57aa5725-1dae-fd7c-0401-c2abbc46c7fb"
			APPKEY = "052fc4636cdfcbd8bc788e0f7fe77e46";
			CRYPTO_SM3_KEY = 'RqEeMmFgk0yWeEme'
			CRYPTO_SM4_KEY = 'yhtInLTEi8WppkRv'
		// }
	}
	//"LDIxOTgxODMwNzEsZTYxMDgzYmMsNzU0MzI4YzFmNGU1LTg0YjAtNTAxYy0yMDUwLWUwNzBjYzBkLDE3MDM4MTE3MTI=" 
	$.DHCRequestJson = function(jsonUrl,successBlock,failureBlock) {
		var xhr = null;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		xhr.onload = function(e) {
			var str = e.target.responseText;
			successBlock(str);
			successBlock = null
			failureBlock = null
			xhr=null
		}
		xhr.onerror = function(e) {
			var errorStr = '服务器请求失败';
			failureBlock(errorStr);
			successBlock = null
			failureBlock = null
			//xhr=null
		}
		xhr.onabort = function(e) {
			var errorStr = '服务器请求中断';
			failureBlock(errorStr);
			successBlock = null
			failureBlock = null
			//xhr=null
		}
		xhr.ontimeout = function(e) {
			var errorStr = '服务器请求超时';
			failureBlock(errorStr);
			successBlock = null
			failureBlock = null
			xhr=null
		}
	
		xhr.open("GET", jsonUrl);
		xhr.setRequestHeader('Content-Type', 'application/json');
		// 发送HTTP请求
		xhr.send();
	}
})(mui);
